package org.airlink.persistence.metamodel
{
	import flash.utils.getQualifiedClassName;
	
	import flex.persistence.EntityManager;
	import flex.persistence.metamodel.Attribute;
	
	import org.airlink.persistence.Entity;
	import org.airlink.persistence.EntityIntrospector;
	import org.airlink.persistence.EntityManagerImpl;
	import org.airlink.persistence.associations.BasicField;
	
	public class AttributeImpl implements Attribute	{
		private var _string:String;
		private var _cls:Class;
		private var _em:EntityManagerImpl;
		private var _aliasIndex:int;
		
		public function AttributeImpl (cls:Class = null, string:String = null, em:EntityManager = null, aliasIndex:int=-1){
			_aliasIndex = aliasIndex;
			_em = em as EntityManagerImpl;		
			_string = string;
			_cls = cls;
		}
		
		public function get name():String{
			return _string;
		}
		
		//TODO : supprimer ou implémenter (inutile jusqu'alors)
		public function get persistentAttributeType():String{
			return null;
		}
		
		
		public function get clazz():Class { 
			return _cls;
		}
		
		public function get entityManager():EntityManager {
			return _em;
		}
		
		public function get aliasIndex():int {
			return _aliasIndex;
		}
	
		
		public function asValue():String{
			var result:String = "";
			if (_aliasIndex == -1)
				result += EntityIntrospector.getSimpleClassName(_cls);
			else
				result += "t" + _aliasIndex.toString();
			result += "." + getColumnName(_cls, _string);	
			return result;
			
		}
		
		public function getColumnName(cls:Class, attributeName:String):String{
			var entity:Entity = _em.introspector.loadMetadata(cls);			
			if(entity.idField.fieldName == attributeName)
				return entity.idField.columnName;
			for each (var basicField:BasicField in entity.basicFields){
				if(basicField.fieldName == attributeName)
					return basicField.columnName;
			}
			return null;
		}

		public function set entityManager(em:EntityManager):void{
			_em = em as EntityManagerImpl;
		}	
		
	}
}